#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<cstring>
#include<thread>

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc <<" serverip serverport" <<std::endl;
}

int sockfd = -1;
std::string serverip;
uint16_t serverport;

void InitClient(const std::string& serverip , uint16_t serverport)
{
    sockfd = socket(AF_INET , SOCK_DGRAM , 0);//创建套接字
    if(sockfd < 0)
    {
        std::cout<< "create socket error" <<std::endl;
    }
}

void recver()
{
    while(true)
    {
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        int m = recvfrom(sockfd , buffer , sizeof(buffer) , 0 ,(struct sockaddr*)&temp , &len);
        if(m > 0)
        {
            buffer[m] = 0;
            std::cerr << buffer <<std::endl;
        }
    }
}

void sender()
{
    struct sockaddr_in server;
    memset(&server , 0 , sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    while(true)
    {
        std::cout << "Please Enter@";
        std::string line;
        std::getline(std::cin,line);//读取

        //发送
        sendto(sockfd , line.c_str() , line.size() , 0, (struct sockaddr*)&server , sizeof(server));
    }
}

// 。/udp_client serverip serverport
int main(int argc , char* argv[])
{
    std::cerr << "hahahaha" <<std::endl;
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    serverip = argv[1];
    serverport = std::stoi(argv[2]);
    InitClient(serverip , serverport);

    std::thread trecv(recver);
    std::thread tsend(sender);

    trecv.join();
    tsend.join();
    return 0;
}